package com.xtck.ha.fault.framework.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class GetPidUtil {
    public static long getPid(String command) throws Exception {
        // 获取 PID（不同系统逻辑不同）
        long pid;
        String os = System.getProperty("os.name").toLowerCase();

        if (os.contains("win")) {
            // Windows 系统：通过 tasklist 匹配进程名获取 PID
            pid = findPidByCommandWindows(command);
        } else {
            // Unix/Linux/Mac：通过反射获取 PID
            pid = findPidByCommandUnix(command);
        }

        System.out.println("脚本进程 PID: " + pid);
        return pid;
    }

    public static String stopByPid(String command) throws Exception {
        // 获取 PID（不同系统逻辑不同）
        long pid;
        String os = System.getProperty("os.name").toLowerCase();

        if (os.contains("win")) {
            // Windows 系统：通过 tasklist 匹配进程名获取 PID
            pid = findPidByCommandWindows(command);
            if (pid == -1)
                return "未查询到对应的服务进程";
            Process process = new ProcessBuilder(
                    "taskkill", "/F","/PID", String.valueOf(pid)
            ).start();
            int exitVal = process.waitFor();
            if (exitVal != 0)
                return "关闭进程 PID:"+ pid+"异常====Exited with error code : " + exitVal;
            else
                return "关闭进程 PID:"+ pid+"成功";
        } else {
            // Unix/Linux/Mac：通过反射获取 PID
            pid = findPidByCommandUnix(command);
            if (pid == -1)
                return "未查询到对应的服务进程";
            Process process = new ProcessBuilder(
                    "kill", "-9", String.valueOf(pid)
            ).start();
            int exitVal = process.waitFor();
            if (exitVal != 0)
                return "关闭进程 PID:"+ pid+"异常====Exited with error code : " + exitVal;
            else
                return "关闭进程 PID:"+ pid+"成功";
        }
    }

    public static Long findPidByCommandUnix(String commandKeyword) throws IOException {
        Process process = new ProcessBuilder(
                "ps", "-ef"
        ).start();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 示例行： "user  1234  5678   0 10:00 pts/0  00:00:00 python app.py"
                if (line.contains(commandKeyword)) {
                    String[] parts = line.trim().split("\\s+");
                    return Long.parseLong(parts[1]); // 第二列为 PID
                }
            }
        }
        return (long)-1;
    }

    // Windows 下通过 wmic 命令获取 PID
    public static Long findPidByCommandWindows(String commandKeyword) throws IOException {
        // 执行 wmic 命令获取进程列表（包含命令行和 PID）
        Process process = new ProcessBuilder(
                "wmic", "process", "where", "name='python.exe'", "get", "processid,commandline"
        ).start();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 匹配命令行中的关键词（如 "app.py"）
                if (line.contains(commandKeyword)) {
                    String[] parts = line.trim().split("\\s+");
                    return Long.parseLong(parts[parts.length - 1]); // 返回 PID
                }
            }
        }
        return (long)-1; // 未找到匹配的进程
    }
}
